const dbCloud = require('../dbCloud.js');
const { db_income } = dbCloud;

/**
 * 获取收入列表
 */
const queryIncomes = async (userId) => {
  return db_income.where({
    _openid: userId
  })
  .orderBy('incomeTime', 'desc')
  .orderBy('updatedAt', 'desc')
  .get();
};

/**
 * 根据主键获取收入
 */
const queryIncomeById = async (id) => {
  return db_income.doc(id).get();
};

/**
 * 根据主键产出收入
 */
const deleteIncomeById = async (id) => {
  return db_income.doc(id).remove();
};

/**
 * 查询所有的收入
 */
const queryAllIncomes = async (userId) => {
  const MAX_LIMIT = 100
  const countResult = await db_income.count();
  const total = countResult.total;
  const batchTimes = Math.ceil(total / MAX_LIMIT);
  const tasks = [];
  for (let i = 0; i < batchTimes; i++) {
    const promise = db_income.skip(i * MAX_LIMIT).limit(MAX_LIMIT).where({
      _openid: userId
    }).get();
    tasks.push(promise);
  }
  return (await Promise.all(tasks)).reduce((acc, cur) => ({
    data: acc.data.concat(cur.data),
    errMsg: acc.errMsg
  }));
};

/**
 * 新增收入
 */
const addIncome = async (params) => {
  return await db_income.add({
    data: {
      incomeType: params.incomeType,
      incomeValue: Number(params.incomeValue),
      incomeTime: params.incomeTime,
      incomeMark: params.incomeMark,
      fileid: params.fileid,
      updatedAt: Date.now(),
      createdAt: Date.now(),
      _openid: params._openid
    }
  });
}

module.exports = {
  queryIncomes,
  queryAllIncomes,
  queryIncomeById,
  deleteIncomeById,
  addIncome
};
